<template>
  <el-dialog :title="title" :modal="false" :visible.sync="open" center :close-on-click-modal="false"
    custom-class="distribution-dialog" :before-close="handleClose">
    <el-container>
      <el-aside class="aside-left">
        <el-scrollbar class="default-scrollbar" wrap-class="default-scrollbar__wrap">
          <el-tree :data="treeData" icon-class="el-icon-arrow-right" node-key="nid" highlight-current
            @node-click="nodeClick" ref="tree" :indent="getIndent()"></el-tree>
        </el-scrollbar>
      </el-aside>
      <el-main>
        <el-table v-if="currentGroup.groupType === 'dispatchgroup'" :data="tableData" height="calc(100% - 1.5vw)"
          cell-class-name="table-cell-custom" header-cell-class-name="table-herder-custom" highlight-current-row
          size="small" @current-change="dispatchCurrentRowChange" style="width: 100%">
          <el-table-column label="姓名" show-overflow-tooltip align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.realName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="职务" show-overflow-tooltip align="center">
            <template slot-scope="scope">
              <span>调度员</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <span>
                {{
                scope.row.agentState === 'login' ? '在线' : '离线'
                }}
              </span>
            </template>
          </el-table-column>
        </el-table>
        <el-table v-else :data="tableData" cell-class-name="table-cell-custom"
          header-cell-class-name="table-herder-custom" highlight-current-row size="small"
          @current-change="currentRowChange" height="calc(100% - 1.5vw)" style="width: 100%">
          <el-table-column label="姓名" show-overflow-tooltip align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.obj ? scope.row.obj.realName : ''}}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="职务" show-overflow-tooltip align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.dutyName }}</span>
            </template>
          </el-table-column> -->
          <el-table-column prop="deviceTel" label="号码" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.deviceTel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="号码状态" align="center">
            <template slot-scope="scope">
              <span>{{ deviceStatusLabel(scope.row.deviceTel) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="号码类型" align="center">
            <template slot-scope="scope">
              <span>{{ deviceTypeLabel(scope.row.deviceType) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-aside class="aside-right">
        <el-scrollbar class="right-scrollbar" wrap-class="right-scrollbar__wrap">
          <div class="input-text">
            <el-input v-model="phoneNumber" size="mini" @keyup.enter.native="handleAdd" placeholder="电话号码">
            </el-input>
            <el-button type="primary" @click="handleAdd">添加</el-button>
          </div>
          <div class="distribution-item" v-for="(row, index) in distributionRow" :key="index" @click="deleteRow(index)">
            <div>{{ row.obj.realName }}</div>
            <div>{{ row.isOperator ? '调度员' : row.deviceTel }}</div>
          </div>
        </el-scrollbar>
        <div class="distribution-commit">
          <el-button @click="videoDispense">开始分发</el-button>
        </div>
      </el-aside>
    </el-container>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { selectDictLabel, guid } from '@/utils/microsys'

export default {
  props: {
    open: Boolean,
    source: Object,
  },
  data() {
    return {
      title: '视频分发',
      tableData: [],
      telMap: new Map(),
      distributionRow: [],
      phoneNumber: '',
      currentGroup: {},
      statusOptions: [
        {
          value: 'online',
          label: '在线',
        },
        {
          value: 'idle',
          label: '空闲',
        },
        {
          value: 'ready',
          label: '准备呼出',
        },
        {
          value: 'ring',
          label: '振铃',
        },
        {
          value: 'talk',
          label: '通话',
        },
        {
          value: 'broadcast',
          label: '广播',
        },
        {
          value: 'hold',
          label: '保持',
        },
        {
          value: 'queue',
          label: '排队',
        },
        {
          value: 'callfail',
          label: '呼叫失败',
        },
        {
          value: 'allowspeak',
          label: '自由发言',
        },
        {
          value: 'banspeak',
          label: '禁止发言',
        },
        {
          value: 'singletalk',
          label: '单独通话',
        },
        {
          value: 'offline',
          label: '离线',
        },
        {
          value: 'monitorring',
          label: '监测振铃',
        },
        {
          value: 'monitortalk',
          label: '监测通话',
        },
      ],
      deviceTypeOptions: [
        {
          value: 'phone',
          label: '话机',
        },
        {
          value: 'hand_microphone',
          label: '手咪',
        },
        {
          value: 'mobile',
          label: '手机号码',
        },
        {
          value: 'home',
          label: '家庭号码',
        },
        {
          value: 'office',
          label: '办公号码',
        },
        {
          value: 'linkage',
          label: '联动号码',
        },
        {
          value: 'wireless',
          label: '无线终端',
        },
        {
          value: 'fax',
          label: '传真号码',
        },
        {
          value: 'soldier',
          label: '单兵终端',
        },
        {
          value: 'poc',
          label: 'POC终端',
        },
        {
          value: 'video',
          label: '视频终端',
        },
      ],
    }
  },
  computed: {
    ...mapGetters({
      deviceStatusMap: 'deviceStatusMap',
      treeData: 'userGroupTreeData',
      telEmployeeMap: 'telEmployeeMap',
      operatorCallTels: 'operatorCallTels',
    }),
  },
  methods: {
    // 树结构间隔
    getIndent() {
      let width = document.body.clientWidth
      return (16 * width) / 1920
    },
    // 获取号码状态
    deviceStatusLabel(deviceTel) {
      const status = this.deviceStatusMap.get(deviceTel)
      if (status) {
        return selectDictLabel(this.statusOptions, status)
      } else {
        return '在线'
      }
    },
    // 号码类型
    deviceTypeLabel(deviceType) {
      return selectDictLabel(this.deviceTypeOptions, deviceType)
    },
    // 视频分发
    videoDispense() {
      if (this.distributionRow.length === 0) {
        this.$message({
          message: '至少选择一位用户',
          type: 'error',
          showClose: true,
          duration: 3 * 1000,
        })
        return
      }

      let mesg_id = guid()
      let form = {
        mesg_id,
      }
      form.target = this.distributionRow.map((row) =>
        row.isOperator
          ? {
              dstUserID: row.obj.operatorID,
            }
          : {
              dstDevice: row.deviceTel,
            }
      )

      if (this.source.type && this.source.type === 'userVideo') {
        form.calledDevice = this.source.videoID
      } else {
        form.flowID = this.source.flowID
        form.videoID = this.source.videoID
      }
      SDK.videoDispense(form)
        .then((res) => {
          sessionStorage.setItem(
            mesg_id,
            JSON.stringify({
              videoID: form.videoID,
              calledDevice: form.calledDevice,
            })
          )
          this.handleClose()
        })
        .catch((err) => {
          this.$message({
            message: '视频分发失败',
            type: 'error',
            showClose: true,
            duration: 3 * 1000,
          })
        })
    },
    // 点击删除
    deleteRow(index) {
      this.$delete(this.distributionRow, index)
    },
    // 添加按钮
    handleAdd() {
      if (this.phoneNumber) {
        const telData = this.telEmployeeMap.get(this.phoneNumber)
        if (!telData) {
          this.distributionRow.push({
            deviceTel: this.phoneNumber,
            obj: {
              realName: '外线',
            },
          })
        } else if (
          !this.distributionRow.some(
            (item) => item.deviceTel === this.phoneNumber
          )
        ) {
          this.distributionRow.push({
            deviceTel: this.phoneNumber,
            obj: telData,
          })
        }
        this.phoneNumber = ''
      }
    },
    // 选中调度员
    dispatchCurrentRowChange(currentRow, oldCurrentRow) {
      if (currentRow) {
        if (currentRow.agentState !== 'login') {
          return this.$message({
            message: '不要选择离线用户',
            type: 'error',
            showClose: true,
            duration: 3 * 1000,
          })
        }
        if (this.operatorCallTels == currentRow.mainTel) {
          return this.$message({
            message: '不能分发给自己',
            type: 'error',
            showClose: true,
            duration: 3 * 1000,
          })
        }
        if (
          !this.distributionRow.some(
            (item) =>
              item.isOperator && item.obj.operatorID === currentRow.operatorID
          )
        ) {
          this.distributionRow.push({
            isOperator: true,
            obj: currentRow,
          })
        }
      }
    },
    // 选中职员
    currentRowChange(currentRow, oldCurrentRow) {
      if (currentRow) {
        const status = this.deviceStatusMap.get(currentRow.deviceTel)
        if (status && status === 'offline') {
          return this.$message({
            message: '不要选择离线用户',
            type: 'error',
            showClose: true,
            duration: 3 * 1000,
          })
        }
        if (
          !this.distributionRow.some(
            (item) => item.deviceTel === currentRow.deviceTel
          )
        ) {
          this.distributionRow.push(currentRow)
        }
      }
    },
    // 点击树节点
    nodeClick(data, node, nodeC) {
      this.currentGroup = data.obj
      SDK.getContactByGroup(data.obj.groupID, data.obj.groupType).then(
        (res) => {
          if (data.obj.groupType === 'dispatchgroup') {
            this.tableData = res.operator
            console.log('res.operator', res.operator)
          } else {
            let tableData = []
            const employeeList = res.employee
            employeeList.forEach((obj) => {
              obj.dutyName = obj.dutyName.join(',')
              for (const telObj of obj.device) {
                if (telObj.deviceTel) {
                  let node = {
                    obj,
                  }
                  node.deviceTel = telObj.deviceTel
                  node.deviceType = telObj.deviceType
                  tableData.push(node)
                }
              }
            })
            this.tableData = tableData
          }
        }
      )
    },
    // 关闭弹出窗
    handleClose() {
      this.$emit('update:open', false)
    },
  },
}
</script>

<style lang="scss" scoped>
@import '~@/assets/scss/distribution.scss';
</style>
